/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.invocation.client;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
@SuppressWarnings("serial")
public class Parameters extends HashMap<String, String> {

    public Parameters() {
    }

    public Parameters(String expr) {
        StringBuilder buf = null;
        String key = null;
        for (int i = 0, len = expr.length(); i < len; i++) {
            char c = expr.charAt(i);
            switch (c) {
            case '=':
                if (key != null || buf == null) {
                    throw new IllegalArgumentException(
                            "Invalid parameters expression: " + expr);
                }
                key = buf.toString();
                buf = null;
                break;
            case ';':
                if (key == null || buf == null) {
                    throw new IllegalArgumentException(
                            "Invalid parameters expression: " + expr);
                }
                put(key, buf.toString());
                key = null;
                buf = null;
                break;
            default:
                if (buf == null) {
                    buf = new StringBuilder();
                }
                buf.append(c);
                break;
            }
        }
        if (key != null && buf != null) {
            put(key, buf.toString());
        }
    }

    public Parameters(int intialCapacity) {
        super(intialCapacity);
    }

    public Parameters(Map<String, String> map) {
        super(map);
    }

    @Override
    public String toString() {
        if (isEmpty())
            return "";
        StringBuilder buf = new StringBuilder();
        for (Map.Entry<String, String> entry : entrySet()) {
            buf.append(entry.getKey()).append('=').append(entry.getValue()).append(
                    ';');
        }
        buf.setLength(buf.length() - 1);
        return buf.toString();
    }

}
